/**
 * Copyright (C) 2012 The SkyTvOS Project
 * <p/>
 * Version     Date           Author
 * ─────────────────────────────────────
 * 2015年1月26日         luwei
 */

package com.coocaa.launcher.wallpaper;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Animatable;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.coocaa.launcher.LauncherBaseActivity;
import com.coocaa.launcher.util.FrescoBitmapFactory;
import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.framework.utils.FastBlur;
import com.coocaa.x.framework.utils.ImageUtils;
import com.coocaa.x.service.litecontent.api.ContentApi;
import com.coocaa.x.service.litecontent.data.store.com_coocaa_theme.RP_WallpaperList;
import com.coocaa.x.uipackage.SkinManager;
import com.coocaa.x.uipackage.utils.CoocaaFresco;
import com.coocaa.x.uipackage.widget.CoocaaDraweeView;
import com.facebook.drawee.controller.BaseControllerListener;
import com.facebook.drawee.controller.ControllerListener;
import com.facebook.drawee.drawable.ScalingUtils;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.imagepipeline.common.ResizeOptions;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import com.tianci.appstore.R;
import com.tianci.appstore.ui.widget.TipToast;
import com.tianci.appstore.utils.SkyConstants;

public class WallpaperPreViewLayout extends FrameLayout implements FrescoBitmapFactory.OnBitmapLoadListener,View.OnClickListener {

    private AnimationButton collectBtn = null;
    private AnimationButton setWallpaper = null;
    private RP_WallpaperList.WallPaper_Item wallPaper_item = null;
    private CoocaaDraweeView draweeView = null;
    private ImageView bottomView = null;
    private boolean isLoading = false;
    private Context mContext = null;

    public WallpaperPreViewLayout(Context context) {
        super(context);
        this.mContext = context;
        addWallpaperView();
        addTopBar();
        addButtonView();
        addTips();
        addButtonLayout();
    }


    private void addWallpaperView() {
        draweeView = new CoocaaDraweeView(mContext);
        addView(draweeView, new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
    }

    private void addTopBar() {
        FrameLayout layout = new FrameLayout(mContext);
        SkinManager.getInstance().setBackgroundResource(layout, R.drawable.statusbar_bg);
        layout.setPadding(0, 0, SkyConstants.Div(25), 0);
        LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, Gravity.TOP);
        addView(layout, params);
        ImageView imageView = new ImageView(mContext);
        LayoutParams params1 = new LayoutParams(SkyConstants.Div(1122), SkyConstants.Div(47), Gravity.CENTER_VERTICAL | Gravity.RIGHT);
        imageView.setImageResource(R.drawable.launcher_wallpaper_preview_top);
        layout.addView(imageView, params1);
        Animation animation = AnimationUtils.loadAnimation(mContext, R.anim.in_updown);
        animation.setDuration(800);
        layout.startAnimation(animation);
    }

    private void addButtonView() {
        bottomView = new ImageView(mContext);
        LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, SkyConstants.Div(283), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
        bottomView.setImageResource(R.drawable.launcher_wallpaper_preview_buttom);
        bottomView.setScaleType(ImageView.ScaleType.FIT_XY);
        addView(bottomView, params);
        Animation animation = AnimationUtils.loadAnimation(mContext, R.anim.in_downup);
        animation.setDuration(800);
        bottomView.startAnimation(animation);
    }

    private void addButtonLayout() {
        LinearLayout layout = new LinearLayout(mContext);
        layout.setGravity(Gravity.CENTER_VERTICAL);
        addCollectButton(layout);
        addsetWallpaperButton(layout);
        LayoutParams params = new LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT,Gravity.CENTER_VERTICAL);
        params.topMargin = CoocaaApplication.Div(-65);
        addView(layout, params);
        Animation animation = AnimationUtils.loadAnimation(mContext, R.anim.in_leftright);
        animation.setDuration(800);
        layout.startAnimation(animation);
    }

    private void addCollectButton(LinearLayout layout) {
        collectBtn = new AnimationButton(mContext);
        collectBtn.setTextColor(Color.WHITE);
        collectBtn.setPadding(0, 0, 0, 0);
        collectBtn.setOnClickListener(this);
        collectBtn.setTextSize(CoocaaApplication.Dpi(28));
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                CoocaaApplication.Div(130), CoocaaApplication.Div(250));
        params.leftMargin = CoocaaApplication.Div(33);
        collectBtn.setText(R.string.setting_collect_wallpaer);
        layout.addView(collectBtn, params);
    }


    private void addsetWallpaperButton(LinearLayout layout) {
        setWallpaper = new AnimationButton(mContext);
        setWallpaper.setTextColor(Color.WHITE);
        setWallpaper.setPadding(0, 0, 0, 0);
        setWallpaper.setOnClickListener(this);
        setWallpaper.setTextSize(CoocaaApplication.Dpi(28));
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                CoocaaApplication.Div(130), CoocaaApplication.Div(250));
        setWallpaper.setText(R.string.setting_set_wallpaer);
        layout.addView(setWallpaper, params);
    }

    private void addTips() {
        TextView view = new TextView(mContext);
        view.setTextColor(Color.WHITE);
        view.setTextSize(CoocaaApplication.Dpi(30));
        LayoutParams params = new LayoutParams(
                CoocaaApplication.Div(484), CoocaaApplication.Div(204),Gravity.CENTER_VERTICAL);
        params.topMargin = CoocaaApplication.Div(0);
        view.setGravity(Gravity.BOTTOM);
        view.setPadding(CoocaaApplication.Div(75), 0, 0, CoocaaApplication.Div(18));
        view.setBackgroundResource(R.drawable.wallpaper_preview_button_bg);
        view.setText(R.string.setting_up_down_change_wallpaper);
        addView(view, params);
        Animation animation = AnimationUtils.loadAnimation(mContext, R.anim.in_leftright);
        animation.setDuration(800);
        view.startAnimation(animation);
    }

    @Override
    public void onClick(View v) {
        if (v.equals(collectBtn.getButton())) {
            if (wallPaper_item.isCollected) {
                boolean success = ContentApi.unCollectWallpaper(wallPaper_item.toJSONString());
                if (success) {
                    collectBtn.setText(R.string.setting_uncollect_wallpaer);
                    collectBtn.setBackgroundId(R.drawable.wallpaper_uncollected_selector);
                    collectBtn.startTextViewAnimation();
                    wallPaper_item.isCollected = !wallPaper_item.isCollected;
                    WallpaperController.getInstance(mContext).updateCollect(wallPaper_item);
                    TipToast.getInstance(mContext).showToast(getResources().getDrawable(R.drawable.do_complete),
                            getResources().getString(R.string.setting_uncollect_wallpapere_success));
                } else {
                    TipToast.getInstance(mContext).showTipToast(getResources().getString(R.string.setting_uncollect_wallpapere_failed));
                }
            } else {
                boolean success = ContentApi.collectWallpaper(wallPaper_item.toJSONString());
                if (success) {
                    collectBtn.setText(R.string.setting_collect_wallpaer);
                    collectBtn.setBackgroundId(R.drawable.wallpaper_collected_selector);
                    collectBtn.startTextViewAnimation();
                    wallPaper_item.isCollected = !wallPaper_item.isCollected;
                    if(WallpaperController.getInstance(mContext).updateCollect(wallPaper_item))
                        TipToast.getInstance(mContext).showToast(getResources().getDrawable(R.drawable.do_complete),
                                getResources().getString(R.string.setting_collect_wallpapere_success));
                    else
                        TipToast.getInstance(mContext).showTipToast(getResources().getString(R.string.setting_collect_wallpapere_failed));
                } else {
                    TipToast.getInstance(mContext).showTipToast(getResources().getString(R.string.setting_collect_wallpapere_failed));
                }
            }
        } else if (v.equals(setWallpaper.getButton())) {
            boolean success = ContentApi.setWallpaper(wallPaper_item.toJSONString());
            if (success) {
                setWallpaper.setBackgroundId(R.drawable.wallpaper_setted_selector);
                setWallpaper.startTextViewAnimation();
                WallpaperManager.getInstance().changeAppBackground(wallPaper_item);
                TipToast.getInstance(mContext).showToast(getResources().getDrawable(R.drawable.do_complete),
                        getResources().getString(R.string.setting_set_wallpapere_success));
                ((LauncherBaseActivity) mContext).finish();
            } else
                TipToast.getInstance(mContext).showTipToast(getResources().getString(R.string.setting_set_wallpapere_failed));
        }
    }

    public void setData(RP_WallpaperList.WallPaper_Item item) {
        this.wallPaper_item = item;
        int width = 1280, height = 720;
        if (item.type.equals("ownwallpaper")) {
            collectBtn.setVisibility(View.GONE);
            setWallpaper.requestFocus();
        }else{
            collectBtn.requestFocus();
        }
        ((LauncherBaseActivity) mContext).showLoading();
        isLoading = true;
        bottomView.setBackgroundDrawable(null);
        draweeView.getHierarchy().setActualImageScaleType(ScalingUtils.ScaleType.FIT_XY);
        ImageRequest request = ImageRequestBuilder.newBuilderWithSource(Uri.parse(item.bigUrl))
                .setResizeOptions(new ResizeOptions(width, height))
                .build();
        DraweeController controller = CoocaaFresco.newDraweeControllerBuilder(mContext)
                .setControllerListener(controllerListener)
                .setOldController(draweeView.getController())
                .setLowResImageRequest(ImageRequest.fromUri(item.smallUrl))
                .setImageRequest(request)
                .build();
        draweeView.setController(controller);
        FrescoBitmapFactory.decodeBitmap(mContext, Uri.parse(item.smallUrl), 384, 216, this);
        if (item.isCollected) {
            collectBtn.setText(R.string.setting_collect_wallpaer);
            collectBtn.setBackgroundId(R.drawable.wallpaper_collected_selector);
        }else {
            collectBtn.setText(R.string.setting_uncollect_wallpaer);
            collectBtn.setBackgroundId(R.drawable.wallpaper_uncollected_selector);
        }
        if (WallpaperManager.getInstance().getCurrent() != null &&
                WallpaperManager.getInstance().getCurrent().bigUrl.equals(item.bigUrl)){
            setWallpaper.setBackgroundId(R.drawable.wallpaper_setted_selector);
        }else{
            setWallpaper.setBackgroundId(R.drawable.wallpaper_unsetted_selector);
        }
    }


    ControllerListener controllerListener = new BaseControllerListener() {
        @Override
        public void onFinalImageSet(String id, Object imageInfo, Animatable animatable) {
            super.onFinalImageSet(id, imageInfo, animatable);
            ((LauncherBaseActivity) mContext).hideLoading();
            isLoading = false;
        }

        @Override
        public void onFailure(String id, Throwable throwable) {
            super.onFailure(id, throwable);
            ((LauncherBaseActivity) mContext).hideLoading();
            isLoading = false;
        }
    };

    private Bitmap blurBitmap = null;


    public RP_WallpaperList.WallPaper_Item getData() {
        return wallPaper_item;
    }

    public void destory() {
        recycleBlurBitmap();
    }

    @Override
    public void loadSuccess(final Bitmap bitmap, String url) {

        ((Activity)mContext).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                recycleBlurBitmap();
                blurBitmap = ImageUtils.changeBitmapBrightness(FastBlur.doBlur(Bitmap.createBitmap(
                        bitmap, 0, 159, 384, 57), 16, true), 0.7f, 0);
                bottomView.setBackgroundDrawable(new BitmapDrawable(blurBitmap));
            }
        });
    }

    @Override
    public void loadFailed(String url) {

    }

    private void recycleBlurBitmap() {
        bottomView.setBackgroundDrawable(null);
        if (blurBitmap != null && !blurBitmap.isRecycled())
            blurBitmap.recycle();
        blurBitmap = null;
    }

    public boolean isLoading() {
        return isLoading;
    }
}
